import swal from 'sweetalert2';
import { Component, OnInit, ViewChild } from '@angular/core';
import { Http } from '@angular/http';
import { Router } from '@angular/router';
import { LazyLoadEvent } from 'primeng/components/common/api';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { TranslateService } from '@ngx-translate/core';

import { ConfigService } from '../../../core/common/config.service';
import { SelectComponent } from '../../../shared/component/ng2-select/select';
import { CustomerService } from '../../crm/service/customer.service';
@Component({
      selector: 'app-adjustaccount',
      templateUrl: './adjustaccount.component.html',
      styleUrls: ['./adjustaccount.component.scss']
})
export class AdJustaccountComponent implements OnInit {
      @ViewChild('adjustForm') public adjustForm;
      @ViewChild('adjustacc') public adjustacc: ModalDirective;
      @ViewChild('adjustSelect') public adjustSelect: SelectComponent;
      @ViewChild('adjustFee') public adjustFee;
      @ViewChild('remark') public remark;

      public adjust = '';
      public records = [];
      public adjust_copy = {
            'total_id': '',
            'total_chnl_id': '',
            'chnl_name': '',
            'fee': '',
            'adjust_type': '0',
            'message': '',
            'able': true,
            'adjust_fee': '',
            'remark': '',
            'adjust_text': ''
      };
      public datedefault: any = {
            begin: '',
            end: ''
      };
      public dateInfo: any = {
            begin: '',
            end: ''
      };
      public datepickerOpts = {
            // minViewMode: 2,
            autoclose: true,
            required: true,
            todayBtn: false,
            todayHighlight: true,
            assumeNearbyYear: true,
            format: 'yyyy-mm-dd',
            startDate: '2017-04-01',
            // endDate: new Date(),
            size: 'small',
            orientation: 'auto',
      };
      public flag = false;
      public flag1 = true;
      public dateInfo_compare: any = {
            begin: '',
            end: ''
      };
      public totalRecords: number;
      public pageSize = 10;
      constructor(public configService: ConfigService, public http: Http, public router: Router,
            private customerService: CustomerService, private translate: TranslateService) {

      }
      ngOnInit() {
            this.datejudge();
            this.translate.get('account.adjustaccount.adjustTypeAll').subscribe((res: any) => {
                  this.adjustSelect.items = [{ id: '0', text: res.adjustOn }, { id: '1', text: res.adjustDown }];
            });
            this.initTableData();
      }
      public datejudge() {
            const date = new Date();
            date.setDate(1);
            // console.log(date);
            this.dateInfo.begin = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
            this.datedefault.begin = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
            let currentMonth = date.getMonth();
            const nextMonth: any = ++currentMonth;
            const nextMonthFirstDay: any = new Date(date.getFullYear(), nextMonth, 1);
            const oneDay: any = 1000 * 60 * 60 * 24;
            const last = new Date(nextMonthFirstDay - oneDay);
            // console.log(last);
            this.dateInfo.end = last.getFullYear() + '-' + (last.getMonth() + 1) + '-' + last.getDate();
            this.datedefault.end = last.getFullYear() + '-' + (last.getMonth() + 1) + '-' + last.getDate();
      }
      public initTableData(): void {
            const url = this.configService.get('url') + '?service=ChnlBillService&method=getChnlBillInfo';
            // let url = "assets/yao.json";
            this.http.post(url, { 'start_date': this.datedefault.begin, 'end_date': this.datedefault.end }).toPromise().then(data => {
                  if (data.json().code === '0000') {
                        // console.log(data);
                        this.adjust = data.json().info;
                        // console.log(this.adjust);
                  }else {
                        console.log(data.json().message);
                  }
            });
      }
      public onRowSelect(data): void {
            // console.log(data);
            this.adjust_copy.total_id = data.data.total_id;
            this.adjust_copy.fee = data.data.fee;
            this.adjust_copy.chnl_name = data.data.chnl_name;
            this.adjust_copy.total_chnl_id = data.data.chnl_id;
            // console.log(this.adjust_copy.total_chnl_id);
      }
      public checkBtn() {
            // this.adjustForm.reset();
            this.adjust_copy.adjust_type = '0';
            this.adjustFee.reset();
            this.remark.reset();
            this.adjust_copy.message = '';
            if (this.adjust_copy.total_id !== '') {
                  this.adjustacc.show();
            } else {
                  this.translate.get('account.adjustaccount.noselect').subscribe((res: any) => {
                        swal(res, '', 'error').catch(swal.noop);
                  });
            }
      }
      // public upDigit(n) {
      //       if (/^\d+(\.)?(\d+)?$/.exec(n)) {
      //             this.adjust_copy.able = false;
      //             const fraction = ['角', '分'];
      //             const digit = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
      //             const unit = [['元', '万', '亿'], ['', '拾', '佰', '仟']];
      //             const head: string = n < 0 ? '欠' : '';
      //             n = Math.abs(n);
      //             let s: any = '';
      //             for (let i = 0; i < fraction.length; i++) {
      //                   s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
      //             }
      //             s = s || '整';
      //             n = Math.floor(n);
      //             for (let i = 0; i < unit[0].length && n > 0; i++) {
      //                   let p: any = '';
      //                   for (let j = 0; j < unit[1].length && n > 0; j++) {
      //                         p = digit[n % 10] + unit[1][j] + p;
      //                         n = Math.floor(n / 10);
      //                   }
      //                   s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
      //             }
      //             this.adjust_copy.message = head + s.replace(/(零.)*零元/, '元').replace(/(零.)+/g, '零').replace(/^整$/, '零元整');
      //       } else {
      //             this.adjust_copy.message = '输入格式错误!';
      //             this.adjust_copy.able = true;
      //       }
      // }
      public upDigit(n) {
            if (/^\d+(\.)?(\d+)?$/.exec(n)) {
                  this.adjust_copy.able = false;
                  this.adjust_copy.message = '';
            } else {
                  this.translate.get('account.adjustaccount.wrongFormat').subscribe((res: any) => {
                        this.adjust_copy.message = res;
                  });
                  this.adjust_copy.able = true;
            }
      }
      public chargeQuery() {
            this.translate.get('account.adjustaccount.adjustnow').subscribe((res: any) => {
                  if (this.adjust_copy.adjust_type === '0') {
                        this.adjust_copy.adjust_text = res.on;
                  } else {
                        this.adjust_copy.adjust_text = res.down;
                  }
                  swal({
                        title: res.areYouSure,
                        text: this.adjust_copy.adjust_text + this.adjust_copy.adjust_fee + res.yuan,
                        type: 'warning',
                        showCancelButton: true,
                        cancelButtonText: res.cancel,
                        confirmButtonColor: '#4C91EA',
                        confirmButtonText: res.confirm
                  }).then(() => {
                        const url = this.configService.get('url') + '?service=ChnlAdjustBillService&method=insertChnlAdjustBill';
                        this.http.post(url, {
                              'total_id': this.adjust_copy.total_id,
                              'total_chnl_id': this.adjust_copy.total_chnl_id,
                              'adjust_type': this.adjust_copy.adjust_type,
                              'adjust_fee': this.adjust_copy.adjust_fee,
                              'remark': this.adjust_copy.remark
                        }).toPromise().then(data => {
                              if (data.json().code === '0000') {
                                    swal({
                                          title: res.success,
                                          text: this.adjust_copy.adjust_text + this.adjust_copy.adjust_fee + res.yuan,
                                          type: 'success',
                                          confirmButtonColor: '#3085d6',
                                          confirmButtonText: res.confirm,
                                          confirmButtonClass: 'btn btn-success',
                                    }).then((e: any) => {
                                          this.adjustacc.hide();
                                          this.initTableData();
                                    }, (dismiss: any) => {
                                          this.adjustacc.hide();
                                          this.initTableData();
                                    }).then(() => {
                                          this.adjust_copy.total_id = '';
                                    });
                              } else {
                                    this.adjust_copy.message = 'error:' + data.json().message;
                              }
                        });
                  });
            });
      }
      public loadData(event: LazyLoadEvent) {
            // setTimeout(() => {
            const pageNum = event.first / event.rows + 1;
            const pageSize = event.rows;
            if (this.flag1) {
                  this.dateInfo_compare.begin = this.dateInfo.begin;
                  this.dateInfo_compare.end = this.dateInfo.end;
            }
            const begin = this.flag ? this.dateInfo.begin : this.dateInfo_compare.begin;
            const end = this.flag ? this.dateInfo.end : this.dateInfo_compare.end;
            this.customerService.getAdjustRecords(begin, end, pageNum, pageSize).subscribe(page => {
                  this.records = page.list;
                  // console.log(this.records);
                  this.totalRecords = page.total;
                  this.records.forEach((item) => {
                        this.translate.get('account.adjustaccount.adjustTypeAll').subscribe((res: any) => {
                              switch (item.adjust_type) {
                                    case '0': item.adjust_type = res.adjustOn;
                                          break;
                                    case '1': item.adjust_type = res.adjustDown;
                                          break;
                              }
                        });
                  });
            });
            // }, 250);
      }
      public searchAdjustRecords() {
            this.flag = true;
            const begin = this.flag ? this.dateInfo.begin : this.dateInfo_compare.begin;
            const end = this.flag ? this.dateInfo.end : this.dateInfo_compare.end;
            this.customerService.getAdjustRecords(begin, end, 1, this.pageSize).subscribe(page => {
                  this.records = page.list;
                  this.totalRecords = page.total;
                  this.records.forEach((item) => {
                        this.translate.get('account.adjustaccount.adjustTypeAll').subscribe((res: any) => {
                              switch (item.adjust_type) {
                                    case '0': item.adjust_type = res.adjustOn;
                                          break;
                                    case '1': item.adjust_type = res.adjustDown;
                                          break;
                              }
                        });
                  });
                  Object.assign(this.dateInfo_compare, this.dateInfo);
                  this.flag = false;
                  this.flag1 = false;
            });
      }
}
